/*
* ===================================================
*
*       Filename:  parser.cc
*
*
*        Created:  12/07/2011 03:18:02 PM
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  durand_y, <durand.yoan@gmail.com>
*
* ===================================================
*/

#include "parser.hh"
#include "error.hh"
#include <cstring>

Parser::Parser ()
{
	std::vector<Token> tok;
	token_list_ = tok;
}


Parser::~Parser ()
{
}

void
Parser::parse_file (std::string file)
{
	std::ifstream file_in;
	std::stringstream is;
	std::string str;
	char	*cstr = new char [file.length () + 1];

	strcpy (cstr, file.c_str ());
	file_in.open (cstr, std::ifstream::in);

	if (file_in.is_open ())
	{
		while (getline (file_in, str))
		{
			if (str.compare ("team") == 0)
			{
				Token t ("team", "");
				token_list_.push_back (t);
				continue;
			}
			if (str.compare ("resource") == 0)
			{
				Token t ("resource", "");
				token_list_.push_back (t);
				continue;
			}
			if (str.compare ("obstacle") == 0)
			{
				Token t ("obstacle", "");
				token_list_.push_back (t);
				continue;
			}
			if (str.compare ("end") == 0)
			{
				Token t ("end", "");
				token_list_.push_back (t);
				continue;
			}
			if (str.compare ("") == 0)
				continue;
			else
			{
				Token t ("", str);
				token_list_.push_back (t);
			}
		}
	}
}

bool
Parser::find_map ()
{
	std::stringstream ss (std::stringstream::in | std::stringstream::out);
	std::string s;
	unsigned int i = 0;
    int x = 0;
   	int y = 0;
	while (i < token_list_.size ())
	{
		if (token_list_[i].get_delim ().compare("") == 0)
		{
			ss << token_list_[i].get_piece ();
			ss >> s;
			ss.ignore ();
			ss >> x;
			ss.ignore ();
			ss >> y;
			if (s.compare ("map") == 0)
				return (true);
			if (s.compare ("seed") == 0)
			{
				if (x < 0)
				{
					Error e (Error::NEGATIVE_SEED);
					throw (e);
				}
			}
			ss.clear ();
		}
		++i;
	}
	Error e (Error::NO_MAP);
	throw (e);
	return (false);
}

bool
Parser::find_team ()
{
	std::stringstream ss (std::stringstream::in | std::stringstream::out);
	std::string s;
	int x = 0;
	unsigned int i = 0;
	int y = 0;

	while (i < token_list_.size ())
	{
		if (token_list_[i].get_delim ().compare ("team") == 0)
		{
			while (token_list_[i].get_delim ().compare ("end") != 0)
			{
				ss << token_list_[i].get_piece ();
				ss >> s;
				ss.ignore ();
				ss >> x;
				ss.ignore ();
				ss >> y;
				if (s.compare ("queen") == 0)
					return (true);
				ss.clear ();
				++i;
			}
			Error e (Error::NO_QUEEN);
			throw (e);
			return (false);
		}
		else
			++i;
	}
	Error e (Error::NO_TEAM);
	throw (e);
	return (false);
}

